﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using digit.Core;

namespace SMS.CDR
{
    public partial class CDRVtel : System.Windows.Forms.Form
    {
        // Fields
        private string CDRDirViettel;
        private IContainer components;
        private int mkFolder;
        private string DateCDR;
        private string PassFTPViettel;
        private string ServerFTPViettel;
        private Timer timeWrite;
        private string UserFTPViettel;
        private TabPage tabViettel;
        private TextBox txtLogWrite;
        private GroupBox gbxViettel;
        private TextBox txtTimeViettel;
        private Label label11;
        private TextBox txtDirViettel;
        private Label label12;
        private TextBox txtPassViettel;
        private Label label13;
        private TextBox txtUserViettel;
        private Label label14;
        private TextBox txtServerViettel;
        private Label label15;
        private TabControl tabFTP;
        private Button btnStartViettel;
        private TabPage tabFTPTransfer;
        private TextBox txtLogFtp;
        private Button btnResendVtel;
        private Button btnExit;
        private Button btnClear;
        private CheckBox chkEnableTransfer;

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.tabViettel = new System.Windows.Forms.TabPage();
            this.btnExit = new System.Windows.Forms.Button();
            this.btnClear = new System.Windows.Forms.Button();
            this.btnStartViettel = new System.Windows.Forms.Button();
            this.txtLogWrite = new System.Windows.Forms.TextBox();
            this.gbxViettel = new System.Windows.Forms.GroupBox();
            this.txtTimeViettel = new System.Windows.Forms.TextBox();
            this.label11 = new System.Windows.Forms.Label();
            this.txtDirViettel = new System.Windows.Forms.TextBox();
            this.label12 = new System.Windows.Forms.Label();
            this.txtPassViettel = new System.Windows.Forms.TextBox();
            this.label13 = new System.Windows.Forms.Label();
            this.txtUserViettel = new System.Windows.Forms.TextBox();
            this.label14 = new System.Windows.Forms.Label();
            this.txtServerViettel = new System.Windows.Forms.TextBox();
            this.label15 = new System.Windows.Forms.Label();
            this.tabFTP = new System.Windows.Forms.TabControl();
            this.tabFTPTransfer = new System.Windows.Forms.TabPage();
            this.btnResendVtel = new System.Windows.Forms.Button();
            this.chkEnableTransfer = new System.Windows.Forms.CheckBox();
            this.txtLogFtp = new System.Windows.Forms.TextBox();
            this.timeWrite = new System.Windows.Forms.Timer(this.components);
            this.tabViettel.SuspendLayout();
            this.gbxViettel.SuspendLayout();
            this.tabFTP.SuspendLayout();
            this.tabFTPTransfer.SuspendLayout();
            this.SuspendLayout();
            // 
            // tabViettel
            // 
            this.tabViettel.Controls.Add(this.btnExit);
            this.tabViettel.Controls.Add(this.btnClear);
            this.tabViettel.Controls.Add(this.btnStartViettel);
            this.tabViettel.Controls.Add(this.txtLogWrite);
            this.tabViettel.Controls.Add(this.gbxViettel);
            this.tabViettel.Location = new System.Drawing.Point(4, 22);
            this.tabViettel.Name = "tabViettel";
            this.tabViettel.Size = new System.Drawing.Size(616, 282);
            this.tabViettel.TabIndex = 2;
            this.tabViettel.Text = "CDR Writer";
            this.tabViettel.UseVisualStyleBackColor = true;
            // 
            // btnExit
            // 
            this.btnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnExit.Location = new System.Drawing.Point(512, 85);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(90, 26);
            this.btnExit.TabIndex = 23;
            this.btnExit.Text = "&Exit";
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            // 
            // btnClear
            // 
            this.btnClear.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnClear.Location = new System.Drawing.Point(512, 52);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(90, 26);
            this.btnClear.TabIndex = 22;
            this.btnClear.Text = "Clear Log";
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // btnStartViettel
            // 
            this.btnStartViettel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnStartViettel.Location = new System.Drawing.Point(512, 16);
            this.btnStartViettel.Name = "btnStartViettel";
            this.btnStartViettel.Size = new System.Drawing.Size(90, 32);
            this.btnStartViettel.TabIndex = 21;
            this.btnStartViettel.Text = "Start";
            this.btnStartViettel.Click += new System.EventHandler(this.btnStartViettel_Click);
            // 
            // txtLogWrite
            // 
            this.txtLogWrite.Location = new System.Drawing.Point(12, 123);
            this.txtLogWrite.Multiline = true;
            this.txtLogWrite.Name = "txtLogWrite";
            this.txtLogWrite.ReadOnly = true;
            this.txtLogWrite.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtLogWrite.Size = new System.Drawing.Size(590, 145);
            this.txtLogWrite.TabIndex = 20;
            // 
            // gbxViettel
            // 
            this.gbxViettel.Controls.Add(this.txtTimeViettel);
            this.gbxViettel.Controls.Add(this.label11);
            this.gbxViettel.Controls.Add(this.txtDirViettel);
            this.gbxViettel.Controls.Add(this.label12);
            this.gbxViettel.Controls.Add(this.txtPassViettel);
            this.gbxViettel.Controls.Add(this.label13);
            this.gbxViettel.Controls.Add(this.txtUserViettel);
            this.gbxViettel.Controls.Add(this.label14);
            this.gbxViettel.Controls.Add(this.txtServerViettel);
            this.gbxViettel.Controls.Add(this.label15);
            this.gbxViettel.Location = new System.Drawing.Point(12, 11);
            this.gbxViettel.Name = "gbxViettel";
            this.gbxViettel.Size = new System.Drawing.Size(482, 100);
            this.gbxViettel.TabIndex = 18;
            this.gbxViettel.TabStop = false;
            this.gbxViettel.Text = "FTP Info";
            // 
            // txtTimeViettel
            // 
            this.txtTimeViettel.Location = new System.Drawing.Point(298, 17);
            this.txtTimeViettel.Name = "txtTimeViettel";
            this.txtTimeViettel.Size = new System.Drawing.Size(60, 20);
            this.txtTimeViettel.TabIndex = 18;
            this.txtTimeViettel.Text = "5";
            // 
            // label11
            // 
            this.label11.Location = new System.Drawing.Point(220, 21);
            this.label11.Name = "label11";
            this.label11.Size = new System.Drawing.Size(77, 16);
            this.label11.TabIndex = 19;
            this.label11.Text = "Timer Interval";
            // 
            // txtDirViettel
            // 
            this.txtDirViettel.Location = new System.Drawing.Point(298, 48);
            this.txtDirViettel.Name = "txtDirViettel";
            this.txtDirViettel.Size = new System.Drawing.Size(171, 20);
            this.txtDirViettel.TabIndex = 16;
            this.txtDirViettel.Text = "D:\\vn1102\\Cdr\\CDRVIETTEL\\";
            // 
            // label12
            // 
            this.label12.Location = new System.Drawing.Point(220, 51);
            this.label12.Name = "label12";
            this.label12.Size = new System.Drawing.Size(74, 16);
            this.label12.TabIndex = 17;
            this.label12.Text = "Client Store";
            // 
            // txtPassViettel
            // 
            this.txtPassViettel.Location = new System.Drawing.Point(98, 72);
            this.txtPassViettel.Name = "txtPassViettel";
            this.txtPassViettel.PasswordChar = '*';
            this.txtPassViettel.Size = new System.Drawing.Size(103, 20);
            this.txtPassViettel.TabIndex = 14;
            this.txtPassViettel.Text = "qm@33n41";
            // 
            // label13
            // 
            this.label13.Location = new System.Drawing.Point(25, 72);
            this.label13.Name = "label13";
            this.label13.Size = new System.Drawing.Size(56, 16);
            this.label13.TabIndex = 15;
            this.label13.Text = "Password";
            // 
            // txtUserViettel
            // 
            this.txtUserViettel.Location = new System.Drawing.Point(98, 44);
            this.txtUserViettel.Name = "txtUserViettel";
            this.txtUserViettel.Size = new System.Drawing.Size(103, 20);
            this.txtUserViettel.TabIndex = 12;
            this.txtUserViettel.Text = "quangminh";
            // 
            // label14
            // 
            this.label14.Location = new System.Drawing.Point(24, 46);
            this.label14.Name = "label14";
            this.label14.Size = new System.Drawing.Size(68, 16);
            this.label14.TabIndex = 13;
            this.label14.Text = "User Name";
            // 
            // txtServerViettel
            // 
            this.txtServerViettel.Location = new System.Drawing.Point(98, 16);
            this.txtServerViettel.Name = "txtServerViettel";
            this.txtServerViettel.Size = new System.Drawing.Size(103, 20);
            this.txtServerViettel.TabIndex = 10;
            this.txtServerViettel.Text = "192.168.226.250";
            // 
            // label15
            // 
            this.label15.Location = new System.Drawing.Point(25, 20);
            this.label15.Name = "label15";
            this.label15.Size = new System.Drawing.Size(56, 16);
            this.label15.TabIndex = 11;
            this.label15.Text = "Server";
            // 
            // tabFTP
            // 
            this.tabFTP.Controls.Add(this.tabViettel);
            this.tabFTP.Controls.Add(this.tabFTPTransfer);
            this.tabFTP.Location = new System.Drawing.Point(9, 3);
            this.tabFTP.Name = "tabFTP";
            this.tabFTP.SelectedIndex = 0;
            this.tabFTP.Size = new System.Drawing.Size(624, 308);
            this.tabFTP.TabIndex = 0;
            // 
            // tabFTPTransfer
            // 
            this.tabFTPTransfer.Controls.Add(this.btnResendVtel);
            this.tabFTPTransfer.Controls.Add(this.chkEnableTransfer);
            this.tabFTPTransfer.Controls.Add(this.txtLogFtp);
            this.tabFTPTransfer.Location = new System.Drawing.Point(4, 22);
            this.tabFTPTransfer.Name = "tabFTPTransfer";
            this.tabFTPTransfer.Padding = new System.Windows.Forms.Padding(3);
            this.tabFTPTransfer.Size = new System.Drawing.Size(616, 282);
            this.tabFTPTransfer.TabIndex = 3;
            this.tabFTPTransfer.Text = "FTP Transfer";
            this.tabFTPTransfer.UseVisualStyleBackColor = true;
            // 
            // btnResendVtel
            // 
            this.btnResendVtel.Location = new System.Drawing.Point(516, 9);
            this.btnResendVtel.Name = "btnResendVtel";
            this.btnResendVtel.Size = new System.Drawing.Size(90, 31);
            this.btnResendVtel.TabIndex = 25;
            this.btnResendVtel.Text = "Re-send";
            this.btnResendVtel.UseVisualStyleBackColor = true;
            this.btnResendVtel.Click += new System.EventHandler(this.btnResendVtel_Click);
            // 
            // chkEnableTransfer
            // 
            this.chkEnableTransfer.AutoSize = true;
            this.chkEnableTransfer.Checked = true;
            this.chkEnableTransfer.CheckState = System.Windows.Forms.CheckState.Checked;
            this.chkEnableTransfer.Location = new System.Drawing.Point(11, 15);
            this.chkEnableTransfer.Name = "chkEnableTransfer";
            this.chkEnableTransfer.Size = new System.Drawing.Size(59, 17);
            this.chkEnableTransfer.TabIndex = 22;
            this.chkEnableTransfer.Text = "Enable";
            this.chkEnableTransfer.UseVisualStyleBackColor = true;
            // 
            // txtLogFtp
            // 
            this.txtLogFtp.Location = new System.Drawing.Point(11, 47);
            this.txtLogFtp.Multiline = true;
            this.txtLogFtp.Name = "txtLogFtp";
            this.txtLogFtp.ReadOnly = true;
            this.txtLogFtp.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtLogFtp.Size = new System.Drawing.Size(595, 228);
            this.txtLogFtp.TabIndex = 21;
            // 
            // timeWrite
            // 
            this.timeWrite.Tick += new System.EventHandler(this.timeWrite_Tick);
            // 
            // CDRVtel
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(644, 320);
            this.Controls.Add(this.tabFTP);
            this.MaximizeBox = false;
            this.Name = "CDRVtel";
            this.Text = "VTEL CDR Writer & Transfer";
            this.Load += new System.EventHandler(this.CDRVtel_Load);
            this.tabViettel.ResumeLayout(false);
            this.tabViettel.PerformLayout();
            this.gbxViettel.ResumeLayout(false);
            this.gbxViettel.PerformLayout();
            this.tabFTP.ResumeLayout(false);
            this.tabFTPTransfer.ResumeLayout(false);
            this.tabFTPTransfer.PerformLayout();
            this.ResumeLayout(false);

        }
        #endregion

        // Methods
        public CDRVtel()
        {
            this.InitializeComponent();
        }

        private void CDRVtel_Load(object sender, EventArgs e)
        {
            this.Text = this.Text + " - " + Util.GetAppSettings("ServiceRange");
            this.DateCDR = Util.GetAppSettings("DateCDR");

            if (DateTime.Now.ToString("dd/MM/yyyy") != this.DateCDR)
            {
                ConfigSettings.WriteSetting("DateCDR", DateTime.Now.ToString("dd/MM/yyyy"));
                this.DateCDR = DateTime.Now.ToString("dd/MM/yyyy");
            }

            this.mkFolder = Util.ToInteger(Util.GetAppSettings("VtelMkF"));
            if (DateTime.Now.Day != this.mkFolder)
            {
                ConfigSettings.WriteSetting("VtelMkF", DateTime.Now.Day.ToString());
                this.mkFolder = DateTime.Now.Day;
            }
        }

        #region Button Events

        private void btnStartViettel_Click(object sender, EventArgs e)
        {
            if (this.btnStartViettel.Text.ToLower() == "start")
            {
                this.timeWrite.Interval = (Convert.ToInt32(this.txtTimeViettel.Text) * 60) * 0x3e8;

                this.txtTimeViettel.Enabled = false;
                this.CDRDirViettel = this.txtDirViettel.Text;
                this.txtDirViettel.Enabled = false;
                this.ServerFTPViettel = this.txtServerViettel.Text;
                this.txtServerViettel.Enabled = false;
                this.UserFTPViettel = this.txtUserViettel.Text;
                this.txtUserViettel.Enabled = false;
                this.PassFTPViettel = this.txtPassViettel.Text;
                this.txtPassViettel.Enabled = false;
                this.btnStartViettel.Text = "Stop";

                if (this.CDRDirViettel.Substring(this.CDRDirViettel.Length - 1) != @"\")
                    this.CDRDirViettel = this.CDRDirViettel + @"\";
                
                if (!Directory.Exists(this.CDRDirViettel))
                    Directory.CreateDirectory(this.CDRDirViettel);
                
                if (!Directory.Exists(this.CDRDirViettel + @"Sent\"))
                    Directory.CreateDirectory(this.CDRDirViettel + @"Sent\");

                if (!Directory.Exists(this.CDRDirViettel + @"NotSent\"))
                    Directory.CreateDirectory(this.CDRDirViettel + @"NotSent\");

                this.WriteCDRVIETTEL();
            }
            else
            {
                this.txtDirViettel.Enabled = true;
                this.txtServerViettel.Enabled = true;
                this.txtUserViettel.Enabled = true;
                this.txtPassViettel.Enabled = true;
                this.btnStartViettel.Text = "Start";
                this.timeWrite.Stop();
            }
        }

        private void btnResendVtel_Click(object sender, EventArgs e)
        {
            string str = DateTime.Now.ToString("yyyyMMdd");
            DirectoryInfo info2 = new DirectoryInfo(this.CDRDirViettel);
            foreach (FileInfo info3 in info2.GetFiles("*.bil"))
            {
                try
                {
                    if (Path.GetFileName(info3.FullName).Length > 12)
                        str = Path.GetFileName(info3.FullName).Substring(3, 8); // Get folder name in file name

                    if (Util.ToInteger(Util.GetAppSettings("VtelMkF")) != DateTime.Now.Day)
                    {
                        ConfigSettings.WriteSetting("VtelMkF", DateTime.Now.Day.ToString());

                        // Make remote folder over FTP
                        this.MakeDir(DateTime.Now.ToString("yyyyMMdd"));
                    }

                    //Upload file
                    bool result = Upload(str, info3.FullName);

                    if (result)
                    {
                        if (!Directory.Exists(this.CDRDirViettel + @"Sent\" + str + @"\"))
                            Directory.CreateDirectory(this.CDRDirViettel + @"Sent\" + str + @"\");

                        info3.MoveTo(this.CDRDirViettel + @"Sent\" + str + @"\" + info3.Name);
                        this.WriteLog("Transfer CDR file " + this.CDRDirViettel + info3.Name + " successfully " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    }
                }
                catch (Exception ex4)
                {
                    this.WriteLog("Transfer CDR error: " + ex4.Message);
                    this.timeWrite.Start();
                    return;
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtLogWrite.Text = "";
            this.txtLogFtp.Text = "";
        }

        #endregion Button Events

        #region Function

        private void WriteCDRVIETTEL()
        {
            this.timeWrite.Stop();
            
            SqlConnection cnn = new SqlConnection(Util.GetAppSettings("ConnStrViettel"));
            SqlCommand cmd = new SqlCommand("vn1102_GetCDR", cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            DataSet dataSet = new DataSet();

            try
            {
                cnn.Open();
                adapter.Fill(dataSet);
            }
            catch (Exception ex)
            {
                this.WriteLog("Cannot get data: " + ex.Message + "\r\n");
                this.timeWrite.Start();
                return;
            }
            finally
            {
                cnn.Close();
            }

            if (dataSet.Tables[0].Rows.Count > 0)
            {
                string fileName = "";
                string str = DateTime.Now.ToString("yyyyMMdd");
                this.CDRDirViettel = this.txtDirViettel.Text.Trim();

                if (!Directory.Exists(this.CDRDirViettel + @"NotSent\" + str))
                    Directory.CreateDirectory(this.CDRDirViettel + @"NotSent\" + str);

                if (!Directory.Exists(this.CDRDirViettel + @"Sent\" + str))
                    Directory.CreateDirectory(this.CDRDirViettel + @"Sent\" + str);

                this.WriteLog("Start writing CDR " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                fileName = this.CDRDirViettel + @"NotSent\" + str + @"\DEC" + DateTime.Now.ToString("yyyyMMddHHmm") + ".bil";
                FileInfo info = new FileInfo(fileName);

                try
                {
                    // Create CDR file
                    using (StreamWriter sw = new StreamWriter(File.Open(fileName, FileMode.CreateNew), System.Text.Encoding.UTF8))
                    {
                        for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
                        {
                            string str2 = dataSet.Tables[0].Rows[i]["ServiceID"].ToString();
                            string str3 = (((((dataSet.Tables[0].Rows[i]["MobileNo"].ToString() + ":") + "84" + str2.Substring(str2.Length - 4) + ":") + "INV:") + Convert.ToDateTime(dataSet.Tables[0].Rows[i]["ResponseTime"]).ToString("yyyyMMddHHmmss") + ":") + Convert.ToDateTime(dataSet.Tables[0].Rows[i]["RequestTime"]).ToString("yyyyMMddHHmmss") + ":") + "1:" + Convert.ToInt32(dataSet.Tables[0].Rows[i]["MsgTotal"].ToString()).ToString();
                            
                            sw.WriteLine(str3);
                        }
                    }
                    this.WriteLog("Finish writing CDR " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    this.WriteLog("Write " + dataSet.Tables[0].Rows.Count.ToString() + " record(s) CDR from DB to file " + fileName);
                }
                catch (Exception ex)
                {
                    // Update CDR Status=0
                    this.UpdateCDRStatus("ConnStrViettel", 0, "", ex.ToString().Substring(0, 250));

                    this.WriteLog("Writing CDR error: " + ex.Message);
                    this.timeWrite.Start();
                    return;
                }
            }
            if (chkEnableTransfer.Checked)
                this.TransferCdr();
            
            this.timeWrite.Start();
        }

        private void TransferCdr()
        {
            try
            {
                string str = DateTime.Now.ToString("yyyyMMdd");

                DirectoryInfo info2 = new DirectoryInfo(this.CDRDirViettel + @"NotSent\" + str + @"\");
                foreach (FileInfo info3 in info2.GetFiles("*.bil"))
                {
                    //if (Path.GetFileName(info3.FullName).Length > 12)
                    //    str = Path.GetFileName(info3.FullName).Substring(3, 8); // Get folder name in file name

                    //if (this.mkFolder != DateTime.Now.Day)
                    //{
                    //    ConfigSettings.WriteSetting("VtelMkF", DateTime.Now.Day.ToString());
                    //    this.mkFolder = DateTime.Now.Day;

                    //    // Make remote folder over FTP
                    //    this.MakeDir(DateTime.Now.ToString("yyyyMMdd"));
                    //}

                    bool result = Upload("", info3.FullName);

                    if (result)
                    {
                        if (!Directory.Exists(this.CDRDirViettel + @"Sent\" + str))
                            Directory.CreateDirectory(this.CDRDirViettel + @"Sent\" + str);

                        info3.MoveTo(this.CDRDirViettel + @"Sent\" + str + @"\" + info3.Name);
                        this.WriteLogFTP("Moved file " + info3.Name + " to " + this.CDRDirViettel + @"Sent\" + str + @"\" + " successfully at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    }
                }
            }
            catch { }
        }

        #region Transfer FTP
        /// <summary>
        /// Method to upload the specified file to the specified FTP Server
        /// </summary>
        /// <param name="filename">file full name to be uploaded</param>
        private bool Upload(string dirname, string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            if (dirname != "")            
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.txtServerViettel.Text.Trim() + "/" + dirname + "/" + fileInf.Name));
            else
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.txtServerViettel.Text.Trim() + "/" + fileInf.Name));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(this.txtUserViettel.Text.Trim(), this.txtPassViettel.Text.Trim());

            // By default KeepAlive is true, where the control connection is not closed after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();

                this.WriteLogFTP("Transfer file " + fileInf.Name + " successful at " + DateTime.Now);

                return true;
            }
            catch (Exception ex)
            {
                this.WriteLogFTP(string.Format("Upload failed: {0}", ex.Message));
                return false;
            }
        }

        private void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.txtServerViettel.Text.Trim() + "/" + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(this.txtUserViettel.Text.Trim(), this.txtPassViettel.Text.Trim());
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();

                this.WriteLogFTP(string.Format("Folder named {0} has created.", dirName));
            }
            catch
            {
                this.WriteLogFTP("Make ftp folder failed, may already!");
            }
        }

        #endregion Transfer FTP

        #region Write Log
        private void WriteLog(string s)
        {
            lock (this.txtLogWrite)
            {
                if ((this.txtLogWrite.TextLength + s.Length) > (int)0x8000)
                {
                    this.txtLogWrite.Clear();
                }
                this.txtLogWrite.AppendText(s + Environment.NewLine);
                this.txtLogWrite.ScrollToCaret();
            }
        }

        private void WriteLogFTP(string s)
        {
            lock (this.txtLogFtp)
            {
                if ((this.txtLogFtp.TextLength + s.Length) > (int)0x8000)
                {
                    this.txtLogFtp.Clear();
                }
                this.txtLogFtp.AppendText(s + Environment.NewLine);
                this.txtLogFtp.ScrollToCaret();
            }
        }
        #endregion Write Log

        #region Functions
        private void UpdateCDRStatus(string cnnStr, byte statusCdr, string CdrIndex, string exStr)
        {
            SqlConnection cnn = new SqlConnection(Util.GetAppSettings(cnnStr));
            SqlCommand cmd = new SqlCommand("vn1102_Update_CDR_Status", cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@CDRStatus", SqlDbType.TinyInt).Value = statusCdr;
            cmd.Parameters.Add("@CDRIndex", SqlDbType.VarChar).Value = CdrIndex;
            cmd.Parameters.Add("@ExceptionString", SqlDbType.VarChar).Value = exStr;

            try
            {
                cnn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                this.WriteLog("Cannot execute SP: " + ex.Message + "\r\n");
                return;
            }
            finally
            {
                cnn.Close();
            }
        }

        public static string RemoveSpecialChar(string unicodeString)
        {
            try
            {
                // Remove VietNamese character
                unicodeString = unicodeString.ToLower();
                unicodeString = Regex.Replace(unicodeString, "[áàảãạâấầẩẫậăắằẳẵặ]", "a");
                unicodeString = Regex.Replace(unicodeString, "[éèẻẽẹêếềểễệ]", "e");
                unicodeString = Regex.Replace(unicodeString, "[iíìỉĩị]", "i");
                unicodeString = Regex.Replace(unicodeString, "[óòỏõọơớờởỡợôốồổỗộ]", "o");
                unicodeString = Regex.Replace(unicodeString, "[úùủũụưứừửữự]", "u");
                unicodeString = Regex.Replace(unicodeString, "[yýỳỷỹỵ]", "y");
                unicodeString = Regex.Replace(unicodeString, "[đ]", "d");

                // Remove space
                unicodeString = unicodeString.Replace(" ", "");

                // Remove special character
                //unicodeString = Regex.Replace(unicodeString, "[`-=+:;'?/><,.]", "");
                unicodeString = Regex.Replace(unicodeString, "[`!-+=?/>.<,{}[]|]\\]", "");

                return unicodeString;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion Functions

        #endregion

        #region Timer Events

        private void timeWrite_Tick(object sender, EventArgs e)
        {
            this.WriteCDRVIETTEL();
        }

        private void timeFTP_Tick(object sender, EventArgs e)
        {
            this.TransferCdr();
        }
        #endregion Timer Events
    }
}